package com.company.cloud.ad.client;

import com.company.cloud.ad.modules.api.response.AdResp;
import com.company.cloud.ad.modules.api.service.AdClientService;
import com.company.cloud.ad.modules.cache.models.AdModel;
import com.company.cloud.ad.modules.cache.service.AdCacheService;
import com.company.cloud.ad.modules.cache.util.AdConvertUtils;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.utils.AuthContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@Service
public class AdClientServiceImpl implements AdClientService {

    @Autowired
    private AdCacheService adCacheService;

    @Override
    public BaseClientResult<List<AdResp>> getAdByPositionNo(String adPositionNo, String companyNo) {
        try {
            List<AdModel> data= adCacheService.getAdByCache(adPositionNo, AuthContextUtils.getCompanyNo());
            List<AdResp> list = new ArrayList<AdResp>();
            if (!CollectionUtils.isEmpty(data)) {
                data.forEach(item->{
                    AdResp resp = AdConvertUtils.getAdResp(item);
                    list.add(resp);
                });
            }
            return BaseClientResult.success(list);
        } catch (Exception e) {
            return BaseClientResult.error(e);
        }
    }

    @Override
    public BaseClientResult<AdResp> getAdById(Integer id) {
        try {
            AdModel model = adCacheService.getAdByIdCache(id);
            return BaseClientResult.success(AdConvertUtils.getAdResp(model));
        } catch (Exception e) {
            return BaseClientResult.error(e);
        }
    }

    @Override
    public BaseClientResult<Map<Integer, AdResp>> getAdMapById(Set<Integer> ids) {
        try {
            Map<Integer, AdResp> map = new HashMap<Integer, AdResp>();
            if (!CollectionUtils.isEmpty(ids)) {
                ids.forEach(id->{
                    AdModel model = adCacheService.getAdByIdCache(id);
                    map.put(model.getId(), AdConvertUtils.getAdResp(model));
                });
            }
            return BaseClientResult.success(map);
        } catch (Exception e) {
            return BaseClientResult.error(e);
        }
    }
}
